require "import"
import "android.content.Context"
import "android.content.Intent"
import "java.util.Locale"
import "android.widget.EditText" -- Dagdag na import

import "android.speech.SpeechRecognizer"
import "android.speech.RecognitionListener"
import "android.speech.RecognizerIntent"
import "java.util.Locale"
import "android.content.Intent"

local substitutionTable = {
    ["chino"] = "Jieshuo"
}

function capitalizeFirstWord(text)
    local firstChar = text:sub(1, 1)
    local restOfString = text:sub(2)
    return firstChar:upper() .. restOfString
end

function substituteWords(text)
    for word, substitution in pairs(substitutionTable) do
        text = text:gsub("%f[%a]" .. word .. "%f[%A]", substitution)
    end
    return text
end

function capitalizeAfterPeriod(text)
    return text:gsub("(%.[%s]*%a)", function(match)
        local char = match:sub(-1)
        local capitalizedChar = char:upper()
        return match:sub(1, -2) .. capitalizedChar
    end)
end

function lowercaseAfterComma(text)
    return text:gsub("(%,[%s]*%a)", function(match)
        local char = match:sub(-1)
        local lowercaseChar = char:lower()
        return match:sub(1, -2) .. lowercaseChar
    end)
end

function addPunctuation(text)
    local lastChar = text:sub(-1)
    local punctuation = { ".", "!", "?" }
    local hasPunctuation = false

    for _, p in ipairs(punctuation) do
        if lastChar == p then
            hasPunctuation = true
            break
        end
    end

    if not hasPunctuation then
        text = text .. "."
    end

    return text
end

function hasInternetConnection()
    local connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE)
    local networkInfo = connectivityManager.getActiveNetworkInfo()
    return networkInfo ~= nil and networkInfo.isConnected()
end

function getEditText()
    local editText = service.getEditText()
    if editText == nil then
        service.speak(" kechirasiz buyerda Matn  yoziladigan maydon mavjud emas.") -- Magsasalita kapag walang edit box na nadetekta
        return nil
    else
        return editText
    end
end

function kill()
    speechRecognizer.destroy()
    speechRecognizer = nil
    return true
end

function startListening()
    if not hasInternetConnection() then
        service.speak("nimadir notoʻgʻri ketdi iltimos internetni teshkiring")
        return false
    end
    
    local verbalizationDetected = false
    
    local editText = getEditText() -- Kunin ang edit text
    
    if editText == nil then
        return false -- Huwag magpatuloy kung walang edit text
    end
    
    speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
    speechListener = RecognitionListener{
        onResults = function(results)
            data = results.getParcelableArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
            if data ~= nil and data.size() > 0 then
                verbalizationDetected = true
                local recognizedText = data.get(0)
                recognizedText = capitalizeFirstWord(recognizedText)
                recognizedText = substituteWords(recognizedText)
                recognizedText = capitalizeAfterPeriod(recognizedText)
                recognizedText = lowercaseAfterComma(recognizedText)
                recognizedText = addPunctuation(recognizedText)
                service.insertText(editText, recognizedText .. "\n")
                service.speak(recognizedText)
            end
            if not verbalizationDetected then
                kill()
                return false
            end
        end,
        onError = function()
            kill()
            return false
        end
    }
    
    recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "UZ_UZ")
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName())
    speechRecognizer.startListening(recognizerIntent)
    speechRecognizer.setRecognitionListener(speechListener)
    
    return true
end

startListening()
return true